import fs from "node:fs";
import fsp from "node:fs/promises";

class Download {
  static download(res, path, filename) {
    res.set({
      "Content-type": "application/octe-stream",
      "Content-Disposition": `attachment; filename=${encodeURIComponent(
        filename
      )}`,
    });
    fs.createReadStream(path).pipe(res);
  }

  static async streamload(req, res, path) {
    let range = req.get("range");
    res.set("Content-Type", "application/octet-stream");
    if (range) {
      let stat = await fsp.stat(path);
      let [start, end] = range.split("=")[1].split("-");
      start = parseInt(start, 10);
      end = end ? parseInt(end, 10) : stat.size - 1;
      res.set({
        "Content-Range": `bytes ${start}-${end}/${stat.size}`,
        "Content-Length": end - start + 1,
        "Accept-Ranges": "bytes",
      });
      res.status(206);
      fs.createReadStream(path, { start, end }).pipe(res);
    } else {
      fs.createReadStream(path).pipe(res);
    }
  }
}

export default Download;
